package image.edge;

import image.edge.EdgeDetector.DIRECCTION;
import image.processing.ImageProcessor;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

import mask.ImageMask;

public class DEdgeDetector extends EdgeDetectorImpl {
	private ImageMask mask;
	private double[][] aEdgeDetectorHorizontal = { 
			{ 1d, 2d, 1d },
			{ 0d, 0d, 0d },
			{ -1d, -2d, -1d }, };
	private double[][] aEdgeDetectorVertical = { 
			{ 1d, 0d, -1d },
			{ 2d, 0d, -2d },
			{ 1d, 0d, -1d }, };
	private double[][] aEdgeDetectorDiagonalR = { 
			{ 2d, 1d, 0d },
			{ 1d, 0d, -1d },
			{ 0d, -1d, -2d }, };
	private double[][] aEdgeDetectorDiagonalL = { 
			{ 0d, 1d, 2d },
			{ -1d, 0d, 1d },
			{ -2d, -1d, 0d }, };

	public DEdgeDetector(BufferedImage src, DIRECCTION direcction) {
		super(src);
		if(direcction ==DIRECCTION.HORIZONTAL)
			this.mask = new ImageMask(aEdgeDetectorHorizontal, 3);
		else if(direcction ==DIRECCTION.VERTICAL)
			this.mask = new ImageMask(aEdgeDetectorVertical, 3);
		else if(direcction ==DIRECCTION.DIAGONALRIGHT)
			this.mask = new ImageMask(aEdgeDetectorDiagonalR, 3);
		else if(direcction ==DIRECCTION.DIAGONALLEFT)
			this.mask = new ImageMask(aEdgeDetectorDiagonalL, 3);
	}

	@Override
	public BufferedImage FindEdges() {
		Double[] gradient;
		Raster inRaster;

		System.out.println("tipo" + src.getType());
		// Only intensity (grey-scale) images supported for the time being
		if (src.getType() != BufferedImage.TYPE_BYTE_GRAY) {
			return null;
		}
		
		// get original image pixels
		inRaster = src.getData();
		
		// Applies this operatorr to find gradient levels for each intensity pixel!
		// does not process padded border edge
		gradient = mask.applyMask(src);

		int[][] samples = new int[ret.getHeight()][ret.getWidth()];

		// builds image based on this gradient magnitude
		for (int y = 0 ; y < ret.getHeight() ; y++) {
			for (int x = 0 ; x < ret.getWidth() ; x++) {
				samples[x][y] =(int) Math.floor((gradient[y*ret.getWidth() + x]) * (gradient[y*ret.getWidth() + x]));
			}
		}
		
		ret = ImageProcessor.LinearRangeCompressionChannel(samples,ret);
		
		return ret;
	}

}
